import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {TemplateService} from '../template.service';
import {GroupService} from '../../group/group.service';
import {NzMessageService} from 'ng-zorro-antd';
import {AliyunOssOutputUrl} from '../../../../config/api';
import {ActivatedRoute, Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {DisplayService} from '../../display/display.service';
import {EditorComponent} from '../../../comm-components/wangeditor/editor.component';
import {AdOssUploadService} from '../../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';

import {ElementRef} from '@angular/core';
import {isInteger} from '../../../../../node_modules/@ng-bootstrap/ng-bootstrap/util/util';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [TemplateService, GroupService, DisplayService]
})
export class AddComponent implements OnInit {
  validateForm: FormGroup;
  loading = false;
  page = 1;
  pageSize = 5;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  _isSpinning = false;
  picSizeInfo = '图片建议 500px * 400px';
  submitStatus = false;
  selectedGroup;
  keyword = '';
  fileList = [];
  picList = [];
  description = '';
  f1 = ['templateCover'];
  default = true;
  editId = null;

  @ViewChild(EditorComponent) editor: EditorComponent;
  shopid: any;

  constructor(
    private fb: FormBuilder,
    private templateService: TemplateService,
    private _message: NzMessageService,
    private router: Router,
    private adOssUploadService: AdOssUploadService,
    private localStorageService: LocalStorageService,
    public element: ElementRef,
    private route: ActivatedRoute
  ) {
    this.validateForm = fb.group({
      name: ['', [Validators.required, Validators.maxLength(30)]],
      sort: ['', [Validators.required, Validators.min(0), Validators.max(99)], this.integerValidators],
      // introduce: ['', [Validators.required]],
      // default: [1, [Validators.required]],
      // template_pic: ['', [Validators.required]],
      // template_info: ['']
    });
  }

  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({ error: true, notInteger: true });
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }

  ngOnInit() {
    this.shopid = this.localStorageService.getShop()['id'];
    this.editId = +this.route.snapshot.queryParams['id'];
    if (this.editId) {
      this.getTemplateInfo(this.editId);
    }
  }

  getTemplateInfo(id) {
    this.templateService.getTemplateInfo(id).subscribe(res => {
      if (res.code === 200) {
        this.validateForm.controls['name'].setValue(res.data.name);
        this.validateForm.controls['default'].setValue(res.data.default);
        this.validateForm.controls['introduce'].setValue(res.data.introduce);
        if (res.data.template_pic) {
          this.validateForm.controls['template_pic'].setValue(res.data.template_pic + '?update=' + new Date().getTime());
          this.picList.push({'src': this.aliyunOssOutputUrl + res.data.template_pic + '?update=' + new Date().getTime()});
          this.fileList.push('pic');
        }
      }
    })
  }


//返回control
  getFormControl(name) {
    return this.validateForm.controls[name];
  }


  picError = false;//图片是否错误
  fileChange(flag) {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
      this.validateForm.controls['template_pic'].setValue('');
    } else {
      this.picError = false;
      if (flag) {
        this.uploadImg();
      }
    }


  }


  PostData(event): void {
    // console.log(event);
  }


  // 传图接口:/v1/common/upload
  // 参数：1.request_uri（/v1/member/goods_extend_template/edit_template） 2.file（数组形式）

  uploadImg() {
    this.fileList.every((val, idx, array) => {
      if (val && val != 'pic') {
        console.log(val);
        this.adOssUploadService.getSignature1(`/v1/common/upload`, '/v1/member/goods_extend_template/edit_template', val, this.element.nativeElement.querySelector('form'))
          .subscribe(res => {
              if (res.code === 200) {
                this.validateForm.controls['template_pic'].setValue(res.data[0]);
                this._message.create('success', '上传图片成功');
              }
            }
          );
      }
      return true;
    });
  }


  goBack() {
    this.router.navigate(['member/template/list']);
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    // this.fileChange(false);

    if (this.validateForm.valid) {
      this.submitStatus = true;
      // this.validateForm.controls.default.setValue(this.validateForm.controls.default.value ? 1 : 0);
      // this.validateForm.value['applet_id'] = this.localStorageService.getNowApplet()['applet_uuid'];
      // this.validateForm.value['user_uuid'] = this.localStorageService.getUserInfo()['user_uuid'];
      this.validateForm.value['shop_id'] = this.localStorageService.getShop()['id'];
      this.editId ? this.validateForm.value['id'] = this.editId : '';
      this.templateService.addOrEditTemplateInfo(this.validateForm.value).subscribe(res => {
        if (res.code === 200) {
          this._message.create('success', this.editId ? '修改成功' : '添加成功');
          this.router.navigate(['member/template/list']);
        } else {
          this._message.create('error', res.message);
          this.submitStatus = false;
        }
      })
    }
  }
}



